package gagak.framework.web.paramresovler.requestparam;

import gagak.framework.web.annonation.Nullable;
import gagak.framework.web.annonation.ValueConstants;
import gagak.framework.web.exception.ServletRequestBindingException;
import gagak.framework.web.param.MethodParameter;
import gagak.framework.web.paramresovler.HandlerMethodArgumentResolver;
import gagak.framework.web.support.request.NativeWebRequest;

import javax.servlet.ServletException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * @program: ce
 * @description: 解析 key-value
 * @author: houhong
 * @create: 2022-12-01 22:28
 */
public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver {


    private final Map<MethodParameter, NamedValueInfo> namedValueInfoCache = new ConcurrentHashMap<MethodParameter, NamedValueInfo>(256);


    public AbstractNamedValueMethodArgumentResolver() {

    }


    /*
     * todo
     *    通过模版方法resolveName从 HttpServletRequest, Http Headers, URI template variables 等等中获取对应的属性值（具体由子类去实现）
     */
    @Override
    @Nullable
    public final Object resolveArgument(MethodParameter parameter, NativeWebRequest webRequest) throws Exception {

        // 创建 MethodParameter 对应的 NamedValueInfo
        NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
        MethodParameter nestedParameter = parameter.nestedIfOptional();

        // name属性（也就是注解标注的value/name属性）这里既会解析占位符，还会解析SpEL表达式，非常强大
        // 因为此时的 name 可能还是被 ${} 符号包裹, 则通过 BeanExpressionResolver 来进行解析
        Object resolvedName = resolveStringValue(namedValueInfo.name);
        if (resolvedName == null) {
            throw new IllegalArgumentException("Specified name must not resolve to null: [" + namedValueInfo.name + "]");
        }


        // 模版抽象方法：将给定的参数类型和值名称解析为参数值。  由子类去实现 此处使用模版方式模式
        // @PathVariable     --> 通过对uri解析后得到的decodedUriVariables值(常用) // TODO: 2022/12/1 暂时不做
        // @RequestParam     --> 通过 HttpServletRequest.getParameterValues(name) 获取（常用）
        // @RequestAttribute --> 通过 HttpServletRequest.getAttribute(name) 获取   <-- 这里的 scope 是 request  TODO: 2022/12/1 暂时不做
        // @SessionAttribute --> 略  TODO: 2022/12/1 暂时不做
        // @RequestHeader    --> 通过 HttpServletRequest.getHeaderValues(name) 获取  TODO: 2022/12/1 暂时不做
        // @CookieValue      --> 通过 HttpServletRequest.getCookies() 获取  TODO: 2022/12/1 暂时不做
        Object arg = resolveName(resolvedName.toString(), nestedParameter, webRequest);

        // 若解析出来值仍旧为null，那就走defaultValue （若指定了的话）
        if (arg == null) {
            // 可以发现：defaultValue也是支持占位符和SpEL的~~~
            if (namedValueInfo.defaultValue != null) {
                arg = resolveStringValue(namedValueInfo.defaultValue);

                // 若 arg == null && defaultValue == null && 非 optional 类型的参数 则通过 handleMissingValue 来进行处理, 一般是报异常
            } else if (namedValueInfo.required) {

                // 它是个protected方法，默认抛出ServletRequestBindingException异常
                // 各子类都复写了此方法，转而抛出自己的异常（但都是ServletRequestBindingException的异常子类）
                handleMissingValue(namedValueInfo.name, nestedParameter, webRequest);
            }

            // handleNullValue是private方法，来处理null值
            // 针对Bool类型有这个判断：Boolean.TYPE.equals(paramType) 就return Boolean.FALSE;
            // 此处注意：Boolean.TYPE = Class.getPrimitiveClass("boolean") 它指的基本类型的boolean，而不是Boolean类型哦~~~
            // 如果到了这一步（value是null），但你还是基本类型，那就抛出异常了（只有boolean类型不会抛异常哦~）
            // 这里多嘴一句，即使请求传值为&bool=1，效果同bool=true的（1：true 0：false） 并且不区分大小写哦（TrUe效果同true）
            arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
        }
        // 兼容空串，若传入的是空串，依旧还是使用默认值（默认值支持占位符和SpEL）
        else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
            arg = resolveStringValue(namedValueInfo.defaultValue);
        }

        // 完成自动化的数据绑定~~~ // TODO: 2022/12/1


        // protected的方法，本类为空实现，交给子类去复写（并不是必须的）
        // 唯独只有PathVariableMethodArgumentResolver把解析处理啊的值存储一下数据到
        // HttpServletRequest.setAttribute中（若key已经存在也不会存储了）
        handleResolvedValue(arg, namedValueInfo.name, parameter, webRequest);
        return arg;
    }

    /*
     * Obtain the named value for the given method parameter.
     */
    private NamedValueInfo getNamedValueInfo(MethodParameter parameter) {
        NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter);
        if (namedValueInfo == null) {
            namedValueInfo = createNamedValueInfo(parameter);
            namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo);
            this.namedValueInfoCache.put(parameter, namedValueInfo);
        }
        return namedValueInfo;
    }

    /*
     * Create the {@link NamedValueInfo} object for the given method parameter. Implementations typically
     * retrieve the method annotation by means of {@link MethodParameter#getParameterAnnotation(Class)}.
     *
     * @param parameter the method parameter
     * @return the named value information
     */
    protected abstract NamedValueInfo createNamedValueInfo(MethodParameter parameter);

    /*
     * Create a new NamedValueInfo based on the given NamedValueInfo with sanitized values.
     */
    private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
        String name = info.name;
        if (info.name.isEmpty()) {
            name = parameter.getParameterName();
            if (name == null) {
                throw new IllegalArgumentException(
                        "Name for argument of type [" + parameter.getNestedParameterType().getName() +
                                "] not specified, and parameter name information not found in class file either.");
            }
        }
        String defaultValue = (ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue);
        return new NamedValueInfo(name, info.required, defaultValue);
    }

    /*
     * Resolve the given annotation-specified value,
     * potentially containing placeholders and expressions.
     */
    @Nullable
    private Object resolveStringValue(String value) {

        return null;
    }

    /*
     * Resolve the given parameter type and value name into an argument value.
     *
     * @param name      the name of the value being resolved
     * @param parameter the method parameter to resolve to an argument value
     *
     * @param request   the current request
     * @return the resolved argument (may be {@code null})
     * @throws Exception in case of errors
     */
    @Nullable
    protected abstract Object resolveName(String name, MethodParameter parameter, NativeWebRequest request)
            throws Exception;

    /*
     * Invoked when a named value is required, but {@link #resolveName(String, MethodParameter, NativeWebRequest)}
     * returned {@code null} and there is no default value. Subclasses typically throw an exception in this case.
     *
     * @param name      the name for the value
     * @param parameter the method parameter
     * @param request   the current request
     * @since 4.3
     */
    protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
            throws Exception {

        handleMissingValue(name, parameter);
    }

    /*
     * Invoked when a named value is required, but {@link #resolveName(String, MethodParameter, NativeWebRequest)}
     * returned {@code null} and there is no default value. Subclasses typically throw an exception in this case.
     *
     * @param name      the name for the value
     * @param parameter the method parameter
     */
    protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException {
        throw new ServletRequestBindingException("Missing argument '" + name +
                "' for method parameter of type " + parameter.getNestedParameterType().getSimpleName());
    }

    /*
     * A {@code null} results in a {@code false} value for {@code boolean}s or an exception for other primitives.
     */
    @Nullable
    private Object handleNullValue(String name, @Nullable Object value, Class<?> paramType) {
        if (value == null) {
            if (Boolean.TYPE.equals(paramType)) {
                return Boolean.FALSE;
            } else if (paramType.isPrimitive()) {
                throw new IllegalStateException("Optional " + paramType.getSimpleName() + " parameter '" + name +
                        "' is present but cannot be translated into a null value due to being declared as a " +
                        "primitive type. Consider declaring it as object wrapper for the corresponding primitive type.");
            }
        }
        return value;
    }

    /*
     * Invoked after a value is resolved.
     *
     * @param arg        the resolved argument value
     * @param name       the argument name
     * @param parameter  the argument parameter type
     * @param webRequest the current request
     */
    protected void handleResolvedValue(@Nullable Object arg, String name, MethodParameter parameter,
                                       NativeWebRequest webRequest) {
    }



    /*
     * protected的内部类  所以所有子类（注解）都是用友这三个属性值的  URI（路径变量）、HttpServletRequest、HttpSession、Header、Cookie…等中根据名称key来获取值
     * 解析方法参数上标注的注解
     */
    protected static class NamedValueInfo {

        private final String name;

        private final boolean required;

        @Nullable
        private final String defaultValue;

        public NamedValueInfo(String name, boolean required, @Nullable String defaultValue) {
            this.name = name;
            this.required = required;
            this.defaultValue = defaultValue;
        }
    }

}